#include <jsoncpp/json/json.h>
#include <string>
#include <sstream>
#include <iostream>
#include <memory>
#include <string>

bool serialize(const Json::Value& val, std::string& body)
{
    std::stringstream ss;

    Json::StreamWriterBuilder swb;
    std::unique_ptr<Json::StreamWriter> sw( swb.newStreamWriter());
    int ret = sw->write(val, &ss);
    if(ret != 0)
    {
        std::cout << "json serialize failed\n" << std::endl;
    }
    body = ss.str();
    return true;
}

bool unserialize(std::string& body, Json::Value& val)
{
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
    std::string errs;
    bool ret = cr->parse(body.c_str(), body.c_str() + body.size(), &val, &errs);
    if(ret == false)
    {
        std::cout << "json unserialize failed\n" << std::endl;
        return false;
    }
    return true;
}

int main()
{
    const char* name = "张三";
    int age = 19;
    const char* sex = "男";
    float score[3] = {89, 79.5, 98};

    Json::Value student;
    student["姓名"] = name;
    student["年龄"] = age;
    student["性别"] = sex;
    student["成绩"].append(score[0]);
    student["成绩"].append(score[1]);
    student["成绩"].append(score[2]);
    Json::Value fav;
    fav["书籍"] = "水浒传";
    fav["运动"] = "打羽毛球";
    student["爱好"] = fav;

    std::string body;
    serialize(student, body);
    std::cout << body << std::endl;

    std::string str = R"({"姓名": "王五", "年龄": 18, "成绩": [19, 23, 45.5]})";
    Json::Value stu;
    bool ret = unserialize(str, stu);
    if(ret == false)
        return -1;
    
    std::cout << "姓名: " << stu["姓名"] << std::endl;
    std::cout << "年龄: " << stu["年龄"] << std::endl;
    int sz = stu["成绩"].size();
    for(int i = 0; i < sz; i++)
    {
        std::cout << "成绩: " << stu["成绩"][i].asFloat() << std::endl;
    }
    return 0;
}